package maa.action.all;

import maa.action.Action;
import maa.action.ActionException;
import maa.action.ActionResult;
import maa.dao.DAOCommand;
import maa.dao.DAOFactory;
import maa.dao.DAOManager;
import maa.database.ConnectionPool;
import maa.entity.Course;
import maa.dao.DAOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

public class ViewCourses implements Action {
    @Override
    public ActionResult execute(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        ConnectionPool connectionPool = ConnectionPool.getInstance();
        DAOManager daoManager = DAOFactory.createDAOManager(connectionPool.getConnection());
        final List<Course> courses = new ArrayList<>();
        DAOCommand command = new DAOCommand() {
            @Override                         // nullpointer catch
            public Object execute(DAOManager daoManager) throws ActionException {
                List<Course> temp;
                try {
                    temp = daoManager.getCourseDAO().findAll();
                } catch (DAOException e) {
                    throw new ActionException("Exception in courseDAO.findAll()");
                }
                courses.addAll(temp);
                return courses;
            }
        };
        daoManager.executeAndClose(command);
        req.setAttribute("courses", courses);
        return new ActionResult("courses");
    }
}
